<!--
 * @Descripttion: (销售订单/GB_Sales_Order)
 * @Author: (admin)
 * @Date: (2025-06-19)
-->
<template>
  <div>
     <AIResponseDialog ref="aiDialog" />
    <el-form :model="queryParams" label-position="right" inline ref="queryRef" v-show="showSearch" @submit.prevent>
       <el-form-item label="客户" prop="cust">
            <el-input v-model="queryParams.cust" placeholder="客户" clearable style="width: 140px" @keyup.enter="handleQuery" />
          </el-form-item>
      <el-form-item>
           <el-form-item label="机型" prop="model">
            <el-input v-model="queryParams.model" placeholder="机型" clearable style="width: 140px" @keyup.enter="handleQuery" />
          </el-form-item> 
          <el-form-item label="操作时间">
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期" 
          value-format="YYYY-MM-DD" ></el-date-picker>
      </el-form-item>
        <el-button icon="search" type="primary" @click="handleQuery">{{ $t('btn.search') }}</el-button>
        <el-button icon="refresh" @click="resetQuery">{{ $t('btn.reset') }}</el-button>
      </el-form-item>
    </el-form>
    <!-- 工具区域 -->
    <el-row :gutter="15" class="mb10">
      <el-col :span="1.5">
        <el-button type="primary" v-hasPermi="['gbsalesorder:add']" plain icon="plus" @click="handleAdd">
          {{ $t('btn.add') }}
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="download" @click="handleExport" v-hasPermi="['gbsalesorder:export']">
          {{ $t('btn.export') }}
        </el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
    </el-row>

    <el-table
      :data="dataList"
      v-loading="loading"
      ref="table"
      border
      header-cell-class-name="el-table-header-cell"
      highlight-current-row
      @sort-change="sortChange"
      >
      <el-table-column prop="xh" label="序号" align="center" v-if="columns.showColumn('xh')"/>
      <el-table-column prop="orderDate" label="订单日期" :show-overflow-tooltip="true"  v-if="columns.showColumn('orderDate')"/>
      <el-table-column prop="orderNo" label="订单号" align="center" :show-overflow-tooltip="true" v-if="columns.showColumn('orderNo')"/>
      <el-table-column prop="cust" label="客户简称" align="center" :show-overflow-tooltip="true" v-if="columns.showColumn('cust')"/>
      <el-table-column prop="model" label="机型" align="center" :show-overflow-tooltip="true" v-if="columns.showColumn('model')"/>
      <el-table-column prop="remark" label="具体事宜" align="center" :show-overflow-tooltip="true" v-if="columns.showColumn('remark')"/>
      <el-table-column prop="actQuantity" label="实际数量" align="center" v-if="columns.showColumn('actQuantity')"/>
      <el-table-column prop="shippedQuantity" label="已出货数" align="center" v-if="columns.showColumn('shippedQuantity')"/>
      <el-table-column prop="unshippedQuantity" label="未出货数" align="center" v-if="columns.showColumn('unshippedQuantity')"/>
      <el-table-column label="操作" width="260">
        <template #default="scope">
          <el-button type="primary" size="small" icon="Lightning" title="详情" @click="handlePreview(scope.row)"></el-button>
          <el-button type="success" size="small" icon="edit" title="编辑" v-hasPermi="['gbsalesorder:edit']" @click="handleUpdate(scope.row)"></el-button>
          <el-button type="danger" size="small" icon="delete" title="删除" v-hasPermi="['gbsalesorder:delete']" @click="handleDelete(scope.row)"></el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />


    <el-dialog :title="title" :lock-scroll="false" v-model="open" >
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="20">
            

          <el-col :lg="12">
            <el-form-item label="订单日期" prop="orderDate">
              <el-date-picker
                v-model="form.orderDate"
                type="date"
                placeholder="选择日期时间"
                value-format="YYYY-MM-DD">
              </el-date-picker>
            </el-form-item>
          </el-col>

          <el-col :lg="12">
            <el-form-item label="订单号" prop="orderNo">
              <el-input v-model="form.orderNo" placeholder="请输入订单号" />
            </el-form-item>
          </el-col>

          <el-col :lg="12">
            <el-form-item label="客户简称" prop="cust">
              <el-input v-model="form.cust" placeholder="请输入客户简称" />
            </el-form-item>
          </el-col>

          <el-col :lg="12">
            <el-form-item label="机型" prop="model">
              <el-input v-model="form.model" placeholder="请输入机型" />
            </el-form-item>
          </el-col>

          <el-col :lg="12">
            <el-form-item label="具体事宜" prop="remark">
              <el-input v-model="form.remark" placeholder="请输入具体事宜" />
            </el-form-item>
          </el-col>

          <el-col :lg="12">
            <el-form-item label="实际数量" prop="actQuantity">
              <el-input v-model="form.actQuantity" placeholder="请输入实际数量" />
            </el-form-item>
          </el-col>

          <el-col :lg="12">
            <el-form-item label="已出货数" prop="shippedQuantity">
              <el-input v-model="form.shippedQuantity" placeholder="请输入已出货数" />
            </el-form-item>
          </el-col>

          <el-col :lg="12">
            <el-form-item label="未出货数" prop="unshippedQuantity">
              <el-input v-model="form.unshippedQuantity" placeholder="请输入未出货数" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer v-if="opertype != 3">
        <el-button text @click="cancel">{{ $t('btn.cancel') }}</el-button>
        <el-button type="primary" :loading="state.submitLoading" @click="submitForm">{{ $t('btn.submit') }}</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="gbsalesorder">
import { listGbSalesOrder,
 addGbSalesOrder, delGbSalesOrder, 
 updateGbSalesOrder,getGbSalesOrder 
 } 
  from '@/api/buss/gbsalesorder.js' 
  import { API_QueryAI } from '@/api/common.js' 
const { proxy } = getCurrentInstance()
import AIResponseDialog from '@/components/AIResponseDialog/index.vue'
const aiDialog = ref()
const ids = ref([])
const loading = ref(false)
const dateRange = ref([])
const showSearch = ref(true)
// const queryParams = reactive({
//   pageNum: 1,
//   pageSize: 10,
//   sort: 'OrderDate',
//   sortType: 'asc',
// })
const columns = ref([
  { visible: true, align: 'center', type: '', prop: 'xh', label: '序号'   },
  { visible: true, align: 'center', type: '', prop: 'orderDate', label: '订单日期'  ,showOverflowTooltip: true  },
  { visible: true, align: 'center', type: '', prop: 'orderNo', label: '订单号'  ,showOverflowTooltip: true  },
  { visible: true, align: 'center', type: '', prop: 'cust', label: '客户简称'  ,showOverflowTooltip: true  },
  { visible: true, align: 'center', type: '', prop: 'model', label: '机型'  ,showOverflowTooltip: true  },
  { visible: true, align: 'center', type: '', prop: 'remark', label: '具体事宜'  ,showOverflowTooltip: true  },
  { visible: true, align: 'center', type: '', prop: 'actQuantity', label: '实际数量'   },
  { visible: true, align: 'center', type: '', prop: 'shippedQuantity', label: '已出货数'   },
  { visible: false, align: 'center', type: '', prop: 'unshippedQuantity', label: '未出货数'   },
  //{ visible: false, prop: 'actions', label: '操作', type: 'slot', width: '160' }
])
const total = ref(0)
const dataList = ref([])
const queryRef = ref()
const defaultTime = ref([new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 2, 1, 23, 59, 59)])


var dictParams = [
]


function getList(){
  loading.value = true 
//  console.log(dateRange) 
  listGbSalesOrder(proxy.addDateRange(queryParams.value, dateRange.value)).then(res => {
    const { code, data } = res
    if (code == 200) {
      dataList.value = data.result
      total.value = data.totalNum
      loading.value = false
    }
  })
}

// 查询
function handleQuery() {
  queryParams.pageNum = 1
  getList()
}

// 重置查询操作
function resetQuery(){
  proxy.resetForm("queryRef")
  handleQuery()
}
// 自定义排序
function sortChange(column) {
  var sort = undefined
  var sortType = undefined

  if (column.prop != null && column.order != null) {
    sort = column.prop
    sortType = column.order

  }
  queryParams.sort = sort
  queryParams.sortType = sortType
  handleQuery()
}

/*************** form操作 ***************/
const formRef = ref()
const title = ref('')
// 操作类型 1、add 2、edit 3、view
const opertype = ref(0)
const open = ref(false)
const state = reactive({
  single: true,
  multiple: true,
  submitLoading: false,
  form: {},
  rules: {
    xh: [{ required: true, message: "序号不能为空", trigger: "blur"    , type: "number"  }],
  },
  options: {
  },
   queryParams: {
    pageNum: 1,
    pageSize: 20,
    model: '',
    cust: '' 
  }
})

const { form, rules,queryParams, options, single, multiple } = toRefs(state)

// 关闭dialog
function cancel(){
  open.value = false
  reset()
}

// 重置表单
function reset() {
  form.value = {
    xh: null,
    orderDate: null,
    orderNo: null,
    cust: null,
    model: null,
    remark: null,
    actQuantity: null,
    shippedQuantity: null,
    unshippedQuantity: null,
  };
  proxy.resetForm("formRef")
}

/**
 * 查看
 * @param {*} row
 */
function handlePreview(row) {
  var data = {
    title: 'GbSalesOrder',
    Prompt: row.model,
  };
 API_QueryAI(data).then((res) => {
    const data = JSON.stringify(res.data.table1[0] || '无') ;
     const prom = JSON.stringify(res.data.table2[0].prompt||'无') ;
   //console.log(data)

    aiDialog.value?.openDialog()
  aiDialog.value?.clearMessages();
  // 准备提示词
  const prompt =  data +prom
// 请从以下几个方面进行分析：
// 1. 库存水平评估
// 2. 可能的补货建议
// 3. 潜在问题分析
// 4. 优化建议
  // 添加用户消息
  aiDialog.value?.addMessage({
    role: 'user',
    content:  prompt  
  })

  // 添加空的AI消息用于流式响应
  aiDialog.value?.addMessage({
    role: 'assistant',
    content: '',
    isStreaming: true
  })

  // 调用DeepSeek API
  aiDialog.value?.queryAI(prompt)
  })
  
}

// 添加按钮操作
function handleAdd() {
  reset();
  open.value = true
  state.submitLoading = false
  title.value = '添加销售订单'
  opertype.value = 1
}
// 修改按钮操作
function handleUpdate(row) {
  reset()
  const id = row.xh || ids.value
  getGbSalesOrder(id).then((res) => {
    const { code, data } = res
    if (code == 200) {
      open.value = true
      title.value = '修改销售订单'
      opertype.value = 2

      form.value = {
        ...data,
      }
    }
  })
}

// 添加&修改 表单提交
function submitForm() {
  proxy.$refs["formRef"].validate((valid) => {
    if (valid) {
      state.submitLoading = true

      if (form.value.xh != undefined && opertype.value === 2) {
        updateGbSalesOrder(form.value).then((res) => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addGbSalesOrder(form.value).then((res) => {
            proxy.$modal.msgSuccess("新增成功")
            open.value = false
            getList()
          })
          .finally(() => {
            setTimeout(() => {
              state.submitLoading = false
            }, 800)
          })
      }
    }
  })
}

// 删除按钮操作
function handleDelete(row) {
  const Ids = row.xh || ids.value

  proxy
    .$confirm('是否确认删除参数编号为"' + Ids + '"的数据项？', "警告", {
      confirmButtonText: proxy.$t('common.ok'),
      cancelButtonText: proxy.$t('common.cancel'),
      type: "warning",
    })
    .then(function () {
      return delGbSalesOrder(Ids)
    })
    .then(() => {
      getList()
      proxy.$modal.msgSuccess("删除成功")
    })
}



// 导出按钮操作
function handleExport() {
  proxy
    .$confirm("是否确认导出销售订单数据项?", "警告", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    })
    .then(async () => {
      await proxy.downFile('/Buss/GbSalesOrder/export', { ...queryParams })
    })
}

handleQuery()
</script>